package com.cloudcc.boot.controller;

import com.cloudcc.boot.entity.sap.SapOrderShippingInfoVo;
import com.cloudcc.boot.service.SapService;
import com.yangzg.cloudcc.openapi.response.base.CloudccOpenApiBaseResponse;
import com.yangzg.cloudcc.openapi.utils.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@Slf4j
@RestController
@RequestMapping(path = "/api/sap")
public class SapToCrmController {

    private final SapService sapService;

    public SapToCrmController(SapService sapService) {
        this.sapService = sapService;
    }

    /**
     * 同步SAP订单发货信息到CRM
     *
     * @param sapOrderShippingInfoVo sap 订单发货信息
     * @return 同步结果
     */
    @PostMapping(value = "/syncOrderShippingInfo", consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<CloudccOpenApiBaseResponse<?>> syncWbsToCrm(@RequestBody SapOrderShippingInfoVo sapOrderShippingInfoVo) {
        log.debug("SAP订单发货信息: {}", JacksonUtils.toJsonString(sapOrderShippingInfoVo));
        CloudccOpenApiBaseResponse<?> cloudccOpenApiBaseResponse = new CloudccOpenApiBaseResponse<>();
        try {
            sapService.writeBackSapOrderShippingInfoToCrm(sapOrderShippingInfoVo);
            cloudccOpenApiBaseResponse.setResult(true);
            cloudccOpenApiBaseResponse.setReturnCode("1");
            log.debug("同步SAP订单发货信息到CRM成功");
        } catch (Exception e) {
            cloudccOpenApiBaseResponse.setResult(false);
            cloudccOpenApiBaseResponse.setReturnCode("0");
            cloudccOpenApiBaseResponse.setReturnInfo(e.getMessage());
            log.error("同步SAP订单发货信息到CRM失败: {}", e.getMessage());
        }
        return ResponseEntity.ok(cloudccOpenApiBaseResponse);
    }


}
